/**
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 *         
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. Unless required by applicable law or
 * agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */
package org.rhok.ncn.common;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.rhok.ncn.R;
import org.rhok.ncn.datatypes.LocationData;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class Utils {
    public static void displayQuitDialog(final Activity a) {
        //Ask the user if they want to quit
        new AlertDialog.Builder(a)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(R.string.quit)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                a.finish();    
            }
        })
        .setNegativeButton(R.string.no, null)
        .show();
    }

    public static void toast(Context common, String text) {
        Toast toast = Toast.makeText(common, text, Toast.LENGTH_SHORT);
        toast.show();
    }

    public static void populateOverlays() {
        updateLocation(CommonData.db().getRowsAndClose(
                System.currentTimeMillis() - TimeUnit.DAYS.toSeconds(1)));
    }
    
    public static void updateLocation(List<LocationData> locs) {
        Message msg = CommonData.handler().obtainMessage();
        msg.obj = locs;
        CommonData.handler().sendMessage(msg);
    }
	
	public static int normalizeStrength(int dbm) {
		// convert dB -> ASU ('RSSI') and clamp to [0-31]
		long t = Math.max(0, Math.min(Math.round((dbm + 113.0) / 2f), 31));
		int ret = (int) t;
		//the conversion should always work because we've forced the value to
		//between 0 and 31 inclusive
		if (ret != t)
			Log.e("SS", String.format("Invalid conversion.  Got %d, expected %d", ret, t));
		
		return ret;
	}
}
